#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include "dataProcessing.h"

int
computeFrequencies (int *s, long size, alphabetArray *frequencies )
{
   int i;
   
   for (i = 0; i < ALPHABET_NUM; i++)
   {
      (*frequencies)[i].freq = 0;
      (*frequencies)[i].c = i;
   }
   
   for (i = 0; i < size; i++)
   {
      (*frequencies)[s[i]].c = s[i];
      (*frequencies)[s[i]].freq++;
   }
    
   for (i = 0; i < ALPHABET_NUM; i++)
      (*frequencies)[i].freq = (*frequencies)[i].freq / size;
    
   return 1;
}
/*
int
rotateAlphabetArray (alphabetArray *frequencies )
{
   letterStat toPut, toSave;
   int i;
   
   toPut = (*frequencies)[0];
   toSave = (*frequencies)[1];
   for (i = 1; i < ALPHABET_NUM-1; i++)
   {      
      (*frequencies)[i] = toPut;
      toPut = toSave;
      toSave = (*frequencies)[i+1];
   }
   (*frequencies)[i] = toPut;
   (*frequencies)[0] = toSave;
   
   return 1;  
}
*/
float
computeIndexOfCoincidence (alphabetArray frequencies, int size)
{
   int i;
   float resul = 0;
   float fi;
      
   for (i = 0;  i < ALPHABET_NUM; i++)
   {
      //printf("Aparaciones letra %d = %g\n", frequencies[i].c, frequencies[i].freq * size);
      fi = frequencies[i].freq * size;
      resul +=  (fi * (fi - 1));
   }
   
   resul = resul / ((size * (size-1)) / ALPHABET_NUM);
   
   //printf("Coeficiente de IC para el texto %g\n", resul);
   
   return resul;
}

letterStat
getMaxFreq (alphabetArray frequencies)
{
   int i;
   letterStat resul;
   
   resul = frequencies[0];
   for (i = 1; i < ALPHABET_NUM; i++)
      if (frequencies[i].freq > resul.freq)
         resul = frequencies[i];
   
   return resul;
}

void
unRotateAndPrint(const int *s, long size, int rotation)
{
   int *tmpS;  
  
   if ((tmpS =malloc(sizeof(int) * size )) == NULL)
      return;
   
   memcpy(tmpS, s, sizeof(int) * size );
      
   unRotate(tmpS, size, rotation);
   printIntArray(tmpS, size);
   free(tmpS);
   return;  
}

void
unRotate(int *s, long size, int rotation)
{
   int i;
   
   for (i = 0; i < size; i++) {
      if (s[i] - rotation >= LETRA_A)
         s[i] = s[i] - rotation;
      else
         s[i] = ALPHABET_NUM - (rotation - s[i]);
   }   
   return;
}

void
printIntArray(int *s, long size)
{
   int i;
   
   for (i = 0; i < size; i++)
   {
      if (s[i] <= LETRA_N)
         printf("%c", 'A' + s[i]);
      else if (s[i] == LETRA_ENIE)
         printf("%c", 209);
      else
         printf("%c", 'A' + s[i]-1);
   }
      
   return;
}
